<?php
include_spip('functions/pdk_common');
require_once(_DIR_PLUGIN_ECATALOGUE.'classes/class.ProductModel.php');

function formulaires_ecatalogue_composite_traiter_dist($id_article) {
    $result = array();
    $p_mdl = pdk_load_class('ProductModel','classes');
    $comp_mdl = pdk_load_class('CompositeArticleModel','classes');
    
    try {
    
    $data = $p_mdl->form_data_from_array($_REQUEST);
    if (!$data['is_separate']) $data['is_separate'] = 0; else $data['is_separate'] = 1; // This is needed for is_separate to be set in 0 when checkbox isn't checked
    if (!$data['is_composite']) $data['is_composite'] = 0; else $data['is_composite'] = 1;
    if (!$p_mdl->update_by_id($id_article, $data, true))
        throw new Exception("Product save fail!");         
    
    // Add components
    if ($selected_articles=_request('selected_articles')) {
        if (lire_config('ecatalogue/articles_select')=='enhanced') {
            include_spip('spip_bonux_fonctions');
            $selected_articles = picker_selected(_request('selected_articles'), 'article');    
        }
        if ($selected_articles) {
            $data = array('id_composite'=>$id_article);
            foreach ($selected_articles as $id_component) {
                if ($id_component == $id_article) continue;
                $data['id_article'] = $id_component;
                $where = array('id_composite='.$data['id_composite'], 'id_article='.$data['id_article']);
                // If such link doesn't exist yet, create it
                if ($comp_mdl->get_total($where)==0)
                    $comp_mdl->insert($data);
                if ($comp_mdl->get_total($where)==0)
                   throw new Exception("Insert component article fail!"); 
            }
        }    
    }
    
    // Delete components
    if ($id_component_delete = _request('id_component_delete')) {
        $where = array('id_composite='.$id_article, 'id_article='.$id_component_delete);        
        $comp_mdl->delete($where);
        if ($comp_mdl->get_total($where)!=0)
            throw new Exception("Delete component article fail!");
    }
    
    // Update components
    if (_request('comp_arts') && is_array(_request('comp_arts'))) {
        foreach (_request('comp_arts') as $comp_art) {            
            if ($comp_art['quantity']>0)
                $comp_mdl->update(array('id_composite='.$id_article, 'id_article='.intval($comp_art['id_article'])), array('quantity'=>intval($comp_art['quantity'])));
            else
                $comp_mdl->delete(array('id_composite='.$id_article, 'id_article='.intval($comp_art['id_article'])));    
        }
    }
    
        $result['message_ok'] = _T('ecatalogue:form_saved');
} catch(Exception $e) {
    $result['message_erreur'] = _T('ecatalogue:form_error');
}
    
    set_request('id_component_delete');
    
    return $result;    
}

?>